package routers

import (
	"ahutoj/web/io/constanct"
	"ahutoj/web/io/response"
	"ahutoj/web/service/originJudge/proxyPool/ip"
	"ahutoj/web/utils"
	"fmt"
	"github.com/gin-contrib/pprof"
	"github.com/gin-gonic/gin"
)

func InitProxyServer() {
	conf := utils.GetConfInstance()

	switch conf.Mode {
	case gin.DebugMode:
		gin.SetMode(gin.DebugMode)
	case gin.ReleaseMode:
		gin.SetMode(gin.ReleaseMode)
	}

	router := gin.Default()
	//router.Use(middlewares.Cors())
	regeisterProxyRouters(router)

	// 注册 pprof 监控 仅仅在 开发阶段可看
	if conf.Mode == gin.DebugMode {
		pprof.Register(router)
	}

	InitRouters(router, fmt.Sprintf("%v:%v", conf.ProxyConfig.Host, conf.ProxyConfig.Port))
	// 404
	router.NoRoute(NotFindRegister)

	router.Run(fmt.Sprintf(":%v", conf.ProxyConfig.Port))
}
func regeisterProxyRouters(router *gin.Engine) {
	// 相当于接口 /api/ 这组路径
	apiRouter := router.Group("/api")
	{
		proxyGroup := apiRouter.Group("/proxy")
		{
			proxyGroup.GET("/all", ProxyAllHandler)
			proxyGroup.GET("/:type", ProxyTypeHandler)
		}
	}
}

func ProxyAllHandler(ctx *gin.Context) {
	response.ResponseOK(ctx, ip.RandomProxy(ctx))
}

func ProxyTypeHandler(ctx *gin.Context) {
	httpType := ctx.Param("type")
	if httpType != "http" && httpType != "https" {
		response.ResponseError(ctx, constanct.ServerErrorCode)
	}
	response.ResponseOK(ctx, ip.RandomByProxyType(ctx, httpType))
}
